package com.ltmonitor.web.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ltmonitor.web.util.JsonMessage;

@Controller
@RequestMapping("/mileageStatistic")
public class MileageStatisticAction extends GenericAction {

	@RequestMapping("/statistic.action")
	@ResponseBody
	public JsonMessage statistic(String queryId, String month, @RequestParam( required = false, defaultValue="0") long depId) {
		try {
			Map params = this.getParams();

			// String strMonth = month > 9 ? (""+month) : ("0" + month);
			// strMonth = year + strMonth;
			// 按部门查询条件，部门及下级部门下的数据
			if (depId > 0) {
				List<Long> depIdList = super.getDepartmentService().getDepIdList(depId);
				params.put("depIdList", depIdList);
				params.remove("depId");
			} else if (this.getOnlineUser().getCompanyId() > 0 && this.getOnlineUser().isSuperAdmin() == false) {
				List<Long> depIdList = super.getDepartmentService().getDepIdList(this.getOnlineUser().getCompanyId());
				params.put("companyIdList", depIdList);
				params.remove("depId");

			} else
				params.remove("depId");

			params.put("month", month);
			params.put("userId", this.getOnlineUser().getEntityId());
			// params.put("depIdList", super.getAuthorizedDepIdList());
			List result = this.queryService.query(queryId, params);
			Collection<Map> c = convert(result);
			return json(true, c);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			return json(false, ex.getMessage());
		}
	}

	private List<Map> convert(List ls) {
		List result = new ArrayList();
		Map<String, Map> staticMap = new LinkedHashMap<String, Map>();
		for (Object obj : ls) {
			Map rowData = (Map) obj;
			String plateNo = "" + rowData.get("plateNo");
			// String plateColor = "" + rowData.get("plateColor");
			// convert(rowData, "plateColor", "plateColor");// 调用基础数据，转换成文字描述
			String depName = "" + rowData.get("depName");
			int day = Integer.parseInt(""+rowData.get("day"));
			//BigDecimal mileage = (BigDecimal) rowData.get("mileage");
			Double mileage = Double.parseDouble(""+ rowData.get("mileage"));
			Map newRowData = staticMap.get(plateNo);
			if (newRowData == null) {
				newRowData = new HashMap();
				// plateColor = "" + rowData.get("plateColor");
				newRowData.put("plateNo", plateNo);
				// newRowData.put("plateColor", plateColor);
				newRowData.put("depName", depName);
				// newRowData.put("staticDate", staticDate);
				staticMap.put(plateNo, newRowData);
			}
			newRowData.put(day, mileage);
		}
		List<Map> res = new ArrayList<Map>();
		res.addAll(staticMap.values());
		return res;
	}

}
